package com.jiayi.furniture.login.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.jiayi.furniture.user.service.IUserServices;
import com.jiayi.furniture.user.User;

@Controller
public class LoginController {
	
	private static String path = "furniture/login/"	;	//jsp路径
	
	@Autowired
	private IUserServices loginService;
	
	/**
	 * 跳转到登陆页面
	 */
	@RequestMapping(value="/login")
	public ModelAndView login(){
		Map<String, String> tmp = new HashMap<String, String>();
		tmp.put("ceshi", "ceshi");
		return new ModelAndView(path+"login",tmp);
	}
	
	/**
	 * 执行登陆动作
	 * @param userName	用户名称
	 * @param account	账号
	 * @param password	密码
	 */
	@RequestMapping(value="/doLogin")
	public ModelAndView logon(HttpServletRequest request,
            HttpServletResponse response,String userName,String account,String password){
		ModelAndView mav = new ModelAndView();
		//将参数封装为对象
		User user = new User() ;
		user.setName(userName);
		user.setAccount(account);
		user.setPassword(password);
		try {
			//检查是否存在该用户名并校验密码
			if(loginService.checkUser(user)){
				user = loginService.getUser(user.getId());
				request.getSession().setAttribute("LoginUser", user);
				mav.setViewName(path+"index");
			}else{
				mav.setViewName(path+"login");
			}
			
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestMapping(value="/logout")
	public ModelAndView logout(HttpServletRequest request,
            HttpServletResponse response){
		try {
			HttpSession session=request.getSession();
			session.removeAttribute("LoginUser");
		} catch (RuntimeException e) {
		}
		return new ModelAndView("/login");
	}
	
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public ModelAndView register(User user){
		Map<String, String> tmp = new HashMap<String, String>();
		loginService.addUser(user);
		return new ModelAndView("login",tmp);
	}
	
	
	@RequestMapping(value="/index")
	public ModelAndView showIndex(HttpServletRequest request,
            HttpServletResponse response){
		
		return new ModelAndView("/index");
	}
}
